<template>
  <a-form
    :model="formState"
    name="basic"
    :label-col="{ span: 1 }"
    :wrapper-col="{ span: 24 }"
    class="w-full"
    autocomplete="off"
    @finish="debouncedLogin"
  >
    <a-form-item
      class="w-100 enter-x"
      :rules="[{ required: true, message: '请输入用户名！' }]"
    >
      <a-input v-model:value="formState.username" placeholder="账号" class="h-10" />
    </a-form-item>
    <a-form-item
      :rules="[{ required: true, message: '请输入密码！' }]"
      class="w-100 enter-x"
    >
      <a-input-password v-model:value="formState.password" placeholder="密码" class="h-10" />
    </a-form-item>
    <a-form-item  class="w-100">
      <a-checkbox v-model:checked="remember" class="enter-x">记住我</a-checkbox>
      <a-typography-link target="_blank" @click="prompt" class="enter-x">
        忘记密码？
      </a-typography-link>
    </a-form-item>
    <a-form-item class="w-100 enter-x">
      <a-button type="primary" html-type="submit" class="w-full" :loading="isSendLoginRequest"
        >登录</a-button
      >
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue';
  import { login as useLogin } from '@/api/user';
  import { useUserInfoStoreWithOut } from '@/stores/modules/userInfo';
  import { UserInfoResponse } from '@/utils/interface';
  import { useDebounceFn } from '@vueuse/core';
  interface form {
    username: string;
    password: string;
  }
  let isSendLoginRequest = ref(false);

  const router = useRouter();
  const formState: form = reactive({
    username: '',
    password: '',
  });
  const userStore = useUserInfoStoreWithOut();
  // 是否记住登录状态
  let remember = ref(true);
  // 点击登录按钮
  const login = async () => {
    try {
      const res: UserInfoResponse | any = await useLogin(formState);
      const { status, userStatus } = res;
      if (status === 200 && userStatus !== 0) {
        message.success('登录成功！');
        router.replace('/home');
        const { username, role } = res.data;
        let setPermissions = role.map((item) => item.role_name) as string[];
        userStore.setUserInfo(remember.value, {
          username,
          permissions: setPermissions,
        });
      }
      isSendLoginRequest.value = false;
    } catch {
      isSendLoginRequest.value = false;
    }
  };
  const debouncedLogin = useDebounceFn(() => {
    isSendLoginRequest.value = true;
    login();
  }, 1000);
  const prompt = () => {
    message.warning('请联系管理员');
  };
</script>
